package yygh.order.Service.imp;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import yygh.hospital.enums.PaymentTypeEnum;
import yygh.hospital.enums.RefundStatusEnum;
import yygh.hospital.model.order.OrderInfo;
import yygh.hospital.model.order.PaymentInfo;
import yygh.hospital.model.order.RefundInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import yygh.order.Mapper.OrderMapper;
import yygh.order.Service.PaymentService;
import yygh.order.Service.RefundInfoService;
import yygh.order.Service.WeixinService;
import yygh.order.utils.ConstantPropertiesUtils;
import yygh.order.utils.HttpClient;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImp implements WeixinService {


    @Autowired
    OrderMapper orderMapper;

    @Autowired
    PaymentService paymentService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RefundInfoService refundInfoService;

    //service层实现微信支付二维码的生成
    @Override
    public Map creatNative(Long orderId) {
        try {
            //首先从redis中获取二维码的数据，若存在，直接返回
            Map paymap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (paymap!=null){
                return  paymap;
            }
            //若redis中不存在二维码的数据，则进行二维码的生成。
            //根据orderId获取对应的支付订单
            OrderInfo order = orderMapper.selectById(orderId);
            //向支付记录数据表中添加支付记录
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            //设置参数，调用微信生成二维码接口。
            //把参数转换成xml格式，使用商户key进行加密
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = order.getReserveDate() + "就诊" + order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1"); //为了测试，统一写成这个值
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");
            //4 调用微信生成二维码接口,httpclient调用
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置map参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //5 返回相关数据
            String xml = client.getContent();
            //转换map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("resultMap:" + resultMap);
            //6 封装返回结果集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url")); //二维码地址
            //把数据存入到redis中
            if (resultMap.get("result_code")!=null){
                redisTemplate.opsForValue().set(orderId.toString(),map,120, TimeUnit.MINUTES);
            }
            return  map;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }

    //Service层，实现订单状态的查询
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
     try {
         //根据订单编号查询订单
         OrderInfo orderInfo = orderMapper.selectById(orderId);
         //创建一个resultMap进行相关参数的封装
        Map<String,String> paramMap=new HashMap<>();
         paramMap.put("appid", ConstantPropertiesUtils.APPID);
         paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
         paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
         paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
         //设置请求内容
         HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
         client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
         client.setHttps(true);
         client.post();
         //返回数据
         String xmlParam = client.getXmlParam();
         Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlParam);
        return  resultMap;
     }catch (Exception e){
         return null;
     }
    }

        //Service层，实现微信退款操作
        @Override
        public Boolean refund(Long orderId) {
            try {
                //首先根据orderId获取支付记录
                PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId,PaymentTypeEnum.WEIXIN);
                //将支付记录对象存道退款记录中
                RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
                //判断是否已经有同样的退款记录了(判断是否已经退款)
                if (refundInfo.getRefundStatus().intValue()== RefundStatusEnum.REFUND.getStatus()){
                    //如果有，则直接返回
                    return  true;
                }
                //如果没有，则调用医院端接口进行退款操作
                //封装需要参数
                Map<String,String> paramMap = new HashMap<>();
                paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
                paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
                paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
                paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
                paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
                paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
    //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
    //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
                paramMap.put("total_fee","1");
                paramMap.put("refund_fee","1");
                String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);

                //调用医院接口进行退款
                //设置调用接口内容
                HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
                client.setXmlParam(paramXml);
                client.setHttps(true);
                //设置证书信息
                client.setCert(true);
                client.setCertPassword(ConstantPropertiesUtils.PARTNER);
                client.post();
                //返回接收数据
                String xmlParam = client.getXmlParam();
                Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlParam);
                if (resultMap!=null&& WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                    refundInfo.setCallbackTime(new Date());
                    refundInfo.setTradeNo(resultMap.get("refund_id"));
                    refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                    refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                    refundInfoService.updateById(refundInfo);
                    return true;
                }
                return false;
            } catch (Exception e) {
                return  false;
            }
        }


}
